import json
import os
import re

from django.conf import settings
import requests
from django.core.files.storage import default_storage, FileSystemStorage
from django.http import HttpResponse, JsonResponse
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView

from django.core.files.storage import default_storage
from django.http import FileResponse, HttpResponseBadRequest
from rest_framework.views import APIView
import mimetypes


# dicts={
#     "Projects":Project,
#
# }
# def extract_project_name_from_path(path_str):
#     # 使用切片方法直接获取项目名
#     parts = path_str.split('/')
#
#     if len(parts) >= 2:
#         project_name = parts[1]  # 获取"Projects"
#         return project_name

# 增加
class FileUploadView(APIView):
    parser_classes = [MultiPartParser]  # 支持文件上传

    def post(self, request):
        try:
            data = request.data
            file_obj = request.FILES.get('file')
            provided_path = data.get('path')
            # 判断并处理相对路径
            if not provided_path.startswith('/'):  # 如果不是绝对路径，则视为相对路径
                abs_path = os.path.join(settings.MEDIA_ROOT, provided_path)  # 将相对路径转换为项目根目录下的绝对路径

                # 创建文件存储对象，并保存文件
                fs = FileSystemStorage(location=abs_path)
                filename = fs.save(file_obj.name, file_obj)

                return JsonResponse(
                    {'message': 'File uploaded successfully  路径  ' + str(provided_path), 'filename': filename},
                    status=201)

            else:
                return JsonResponse({'error': 'Invalid path. Only relative paths are allowed.'}, status=400)

        except KeyError:  # 没有找到'file'字段
            return JsonResponse({'error': 'Both file and path are required'}, status=400)
        except Exception as e:
            return JsonResponse({'error': f'Failed to save the file: {str(e)}'}, status=500)


# 查询
class DownloadAndViewFileAPIView(APIView):
    def post(self, request):
        try:
            data = request.data
            file_url = data.get('file_url')

            if not file_url:
                return Response({"error": "File URL is required."}, status=403)
            # 假设file_url是相对于FILES_URL的本地存储路径
            full_file_path = os.path.join(settings.MEDIA_ROOT, file_url.lstrip('/'))
            # 检查文件是否存在
            if not default_storage.exists(full_file_path):
                raise Exception(f"The requested file does not exist: {full_file_path}")
            # 获取文件的MIME类型
            content_type, _ = mimetypes.guess_type(full_file_path)
            # 返回文件响应
            response = FileResponse(open(full_file_path, 'rb'), content_type=content_type)
            # 获取文件后缀名
            file_extension = os.path.splitext(full_file_path)[1]
            response['Content-Disposition'] = f'attachment; filename="download{file_extension}"'
            return response

        except Exception as e:
            return HttpResponseBadRequest(str(e))


# 查询目录文件
class DirectoryContentView(APIView):
    def post(self, request):
        # 获取请求体中的路径
        path_data = request.data.get('path', None)

        if not path_data:
            return JsonResponse({'error': 'Path is required.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 验证并处理路径（根据实际情况调整）
            path = os.path.abspath(settings.MEDIA_ROOT + '/' + path_data)
            print(path)

            # 检查路径是否存在及是否为目录
            if not os.path.exists(path) or not os.path.isdir(path):
                return JsonResponse({'error': 'Invalid directory.'}, status=status.HTTP_400_BAD_REQUEST)

            # 获取该目录下的一级文件和目录列表
            contents = [os.path.join(path, item) for item in os.listdir(path)]
            # 过滤出一级目录
            directories = [content for content in contents if os.path.isdir(content)]

            # 返回结果，这里只返回目录名，不包含完整路径
            result = [{'name': os.path.basename(directory)} for directory in directories]
            files = [{'name': os.path.basename(file)} for file in contents if os.path.isfile(file)]
            return JsonResponse({'directories': result, 'files': files}, status=status.HTTP_200_OK)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 删除文件
class DeleteFileAPIView(APIView):
    def post(self, request):
        try:
            data = request.data
            file_url = data.get('file_url')
            if not file_url:
                return Response({"error": "给我文件路径"}, status=403)
            # 假设file_url是相对于FILES_URL的本地存储路径
            full_file_path = os.path.join(settings.MEDIA_ROOT, file_url.lstrip('/'))
            # 检查文件是否存在
            if not default_storage.exists(full_file_path):
                raise Exception(f"文件不存在啊: {full_file_path}")
            # 删除文件
            default_storage.delete(full_file_path)
            return Response({"sucess": "成功删除"}, status=200)

        except Exception as e:
            return Response({"error": str(e)}, status=400)
